/*
 * @(#)Compiler.java
 * 2011-7-21 下午11:09:21
 *
 * Copyright (c) 2018-2028, HangZhou QiYun InfoTech Co.,Ltd. .
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.qyxx.platform.gsc.parse;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.tools.JavaCompiler;
import javax.tools.JavaFileManager.Location;

import com.qyxx.platform.common.module.dao.HibernateUtils;
import com.qyxx.platform.common.orm.PropertyFilter;
import com.qyxx.platform.common.utils.spring.SpringContextHolder;
import com.qyxx.platform.gsmng.common.service.GsMngManager;

import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.StandardLocation;
import javax.tools.ToolProvider;

/**
 * 
 * @author gxj
 * @version 1.0
 * @since 1.6 2011-7-21 下午11:09:21
 */

public class Compiler {

	public static void test() {
		// TODO Auto-generated method stub
		String fullQuanlifiedFileName = "E:/03-workspace/jiawasoft/jiawasoft/jiawasoft-web/src/main/java/com/jiawasoft/gsweb/gsc/parse/Compiler.java";
		JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
		FileOutputStream err;
		try {
			err = new FileOutputStream("E:/err.txt");
			int compilationResult = compiler.run(null, null, err,
					"-verbose", fullQuanlifiedFileName);
			if (compilationResult == 0) {
				System.out.println("Done");
			} else {
				System.out.println("Fail");
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static void test1() throws Exception {
		String filePath = "E:/05-Product/03-ERP/Source/test/";
		String entityName = filePath + "entity/Test.java";
		String daoName = filePath + "dao/TestDao.java";
		String serviceName = filePath + "service/TestManager.java";
		String actionName = filePath + "web/TestAction.java";
		JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
		StandardJavaFileManager fileManager = compiler
				.getStandardFileManager(null, null, null);
		
		Location location = StandardLocation.CLASS_OUTPUT;  
        File[] outputs = new File[]{new File("E:/03-workspace/jiawasoft/jiawasoft/jiawasoft-web/target/classes")};  
        try {  
            fileManager.setLocation(location, Arrays.asList(outputs));  
        } catch (IOException e) {  
            e.printStackTrace();  
        }
/*        StringBuilder classStr = new StringBuilder("package com.qyxx.platform.gsc.parse;");
		classStr.append("public class TestImpl implements Test { ");
        classStr.append("public void test() {");  
        classStr.append("System.out.println(\"Foo2\");");
        classStr.append("}");
        classStr.append("}");
        JavaFileObject jfo = new StringObject("com.qyxx.platform.gsc.parse.TestImpl", classStr.toString());  */
        
		Iterable<? extends JavaFileObject> files = fileManager
				.getJavaFileObjectsFromStrings(Arrays
						.asList(entityName, daoName, serviceName, actionName));
		JavaCompiler.CompilationTask task = compiler.getTask(null,
				fileManager, null, null, null, files);

		Boolean result = task.call();
		System.out.println("11111");
		if (result) {
			try {
				System.out.println("start Succeeded");
				SpringContextHolder.rebuildSessionFactory();
				/*Test t = (Test) Class.forName("com.qyxx.platform.gsc.parse.TestImpl").newInstance();  
                t.test(); */
				System.out.println("end Succeeded");
				/*Class<?> obj = Class.forName("com.qyxx.platform.gsmng.test.entity.Test");
				SessionFactory sf = null;
				SchemaExport export = new SchemaExport(new AnnotationConfiguration().addAnnotatedClass(obj)
			     .configure("/applicationContext-test.xml")); 
				export.create(true, true);*/
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		} else {
			System.out.println("start1 Succeeded");
			//SpringContextHolder.rebuildSessionFactory();
			System.out.println("end1 Succeeded");
		}
	}
	
	
	public static void test2() throws Exception {
		// TODO Auto-generated method stub
		StringBuilder classStr = new StringBuilder("package com.qyxx.platform.gsc.parse;");
		classStr.append("public class TestImpl implements Test { ");
        classStr.append("public void test() {");  
        classStr.append("System.out.println(\"Foo2\");");
        classStr.append("}");
        classStr.append("}");
        JavaCompiler jc = ToolProvider.getSystemJavaCompiler();  
        StandardJavaFileManager fileManager = jc.getStandardFileManager(null, null, null);  
        Location location = StandardLocation.CLASS_OUTPUT;  
        File[] outputs = new File[]{new File("E:/03-workspace/jiawasoft/jiawasoft/jiawasoft-web/target/classes")};  
        try {  
            fileManager.setLocation(location, Arrays.asList(outputs));  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
          
        JavaFileObject jfo = new StringObject("com.qyxx.platform.gsc.parse.TestImpl", classStr.toString());  
        JavaFileObject[] jfos = new JavaFileObject[]{jfo};  
        Iterable<? extends JavaFileObject> compilationUnits = Arrays.asList(jfos);  
        boolean b = jc.getTask(null, fileManager, null, null, null, compilationUnits).call();  
        if(b){//如果编译成功  
           /* try {  
                Test t = (Test) Class.forName("com.qyxx.platform.gsc.parse.TestImpl").newInstance();  
                t.test();  
            } catch (InstantiationException e) {  
                e.printStackTrace();  
            } catch (IllegalAccessException e) {  
                e.printStackTrace();  
            } catch (ClassNotFoundException e) {  
                e.printStackTrace();  
            }  */
        }  
    } 
	
	public static void test3() throws Exception {
		String sourcePath = "E:/05-Product/03-ERP/Source/test/";
		String targetPath = "E:/03-workspace/jiawasoft/jiawasoft/jiawasoft-web/target/classes";
		String libPath = "E:/03-workspace/jiawasoft/jiawasoft/jiawasoft-web/target/gsweb-1.0.0/WEB-INF/lib";
		boolean flag = CompileUtil.compilePackage(sourcePath, targetPath, null);
		if(flag) {
			SpringContextHolder.rebuildSessionFactory();
		}
	}

	public static void test4(String aa, String... s) {
		List<String> urls = new ArrayList<String>();
		urls.add("E:/05-Product/03-ERP/Source/MainEntity.hbm.xml");
		urls.add("E:/05-Product/03-ERP/Source/SubEntity.hbm.xml");
		HibernateUtils.updateHibernateCfg(urls, true);
		
		GsMngManager gsMngManager = (GsMngManager)SpringContextHolder.getBean("gsMngManager");
		gsMngManager.setEntityName("MainEntity");
		
		List<Map<String, Object>> list = gsMngManager.findList(new ArrayList<PropertyFilter>());
		for(Map<String, Object> obj : list) {
			for(Map.Entry<String, Object> me : obj.entrySet()) {
				System.out.println(me.getKey() + ":" + me.getValue());
			}
			System.out.println(obj.get("subEntitys"));
		}
		
		urls = new ArrayList<String>();
		urls.add("E:/05-Product/03-ERP/Source/MainEntity1.hbm.xml");
		urls.add("E:/05-Product/03-ERP/Source/SubEntity1.hbm.xml");
		HibernateUtils.updateHibernateCfg(urls, true);
		
		Map<String, Object> obj1 = new HashMap<String, Object>();
		obj1.put("itemSubject", "222");
		obj1.put("itemDescp", "adfadf");
		obj1.put("createtime", new Date());
		
		
		Map<String, Object> subObj = new HashMap<String, Object>();
		subObj.put("subject", "sdfasdf");
		subObj.put("addCol", "adfadf111f111");
		subObj.put("createtime", new Date());
		subObj.put("mainEntity", obj1);
		
		
		Map<String, Object> subObj1 = new HashMap<String, Object>();
		subObj1.put("subject", "2222sdfasdf");
		subObj1.put("addCol", "2222adfadf111f111");
		subObj1.put("createtime", new Date());
		subObj1.put("mainEntity", obj1);
		
		List<Map<String, Object>> subObjList = new ArrayList<Map<String, Object>>();
		subObjList.add(subObj);
		subObjList.add(subObj1);
		obj1.put("subEntitys", subObjList);
		gsMngManager.saveEntity(obj1, null);
		
		List<Map<String, Object>> list2 = gsMngManager.findList(new ArrayList<PropertyFilter>());
		for(Map<String, Object> obj : list2) {
			for(Map.Entry<String, Object> me : obj.entrySet()) {
				System.out.println(me.getKey() + ":" + me.getValue());
			}
			System.out.println(obj.get("subEntitys"));
		}
	}
	
	public static void test5() {
		List<String> urls = new ArrayList<String>();
		urls.add("E:/05-Product/03-ERP/Source/ContractsHead.hbm.xml");
		urls.add("E:/05-Product/03-ERP/Source/ContractsSheet.hbm.xml");
		HibernateUtils.updateHibernateCfg(urls, true);
		
		GsMngManager gsMngManager = (GsMngManager)SpringContextHolder.getBean("gsMngManager");
		gsMngManager.setEntityName("ContractsHead");
		
		List<Map<String, Object>> list2 = gsMngManager.findList(new ArrayList<PropertyFilter>());
		for(Map<String, Object> obj : list2) {
			for(Map.Entry<String, Object> me : obj.entrySet()) {
				System.out.println(me.getKey() + ":" + me.getValue());
			}
			System.out.println(obj.get("contractsSheet"));
		}
	}
	
	/**
	 * 
	 * @param args
	 * @throws Exception 
	 * @throws FileNotFoundException
	 */
	public static void main(String[] args) {
		try {
			test4("");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
